package com.banciyuan.bcywebview.biz.detail.complex.holder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.lock.IlockedInter;
import com.banciyuan.bcywebview.biz.detail.lock.LockedHelper;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.post.cos.CosEditActivity;
import com.banciyuan.bcywebview.biz.post.illust.illustEditActivity;
import com.banciyuan.bcywebview.biz.post.write.EditArticleActivity;
import com.banciyuan.bcywebview.biz.write.DailyEditActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.file.ByteUtils;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.io.File;

import de.greenrobot.daoexample.model.Complex;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Profile;

/**
 * Created by squall on 2016/8/10.
 */
public class HeaderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private ImageView bg_iv;
    private ImageView blur_iv;
    private ImageView back_iv;
    private ImageView circle_iv;
    private ImageView vip_iv;
    private LinearLayout viewCounts_ll;
    private LinearLayout needFans_ll;
    private RelativeLayout lock_rl;
    private TextView focus_tv;
    private TextView setFans_tv;
    private TextView viewCounts_tv;
    private TextView name_tv;
    private TextView time_tv;
    private TextView intro_tv;
    private LinearLayout lockcontral_ll;
    private TextView lockReason_tv;
    private TextView lockUpdate_tv;
    private TextView lockPost_tv;
    private TextView lockCheck_tv;
    private RelativeLayout head_rl;

    private Context mContext;
    private Complex complex;
    private ImageView ivHeaderRightAction;

    private LinearLayout login_ll;
    private TextView login_tv;


    public HeaderHolder(View itemView) {
        super(itemView);
        bg_iv = (ImageView) itemView.findViewById(R.id.detail_headbg_img);
        blur_iv = (ImageView) itemView.findViewById(R.id.iv_flur);
        back_iv = (ImageView) itemView.findViewById(R.id.iv_back_top);
        circle_iv = (ImageView) itemView.findViewById(R.id.detail_head_img);
        vip_iv = (ImageView) itemView.findViewById(R.id.vip_logo);
        focus_tv = (TextView) itemView.findViewById(R.id.tv_focuse);
        setFans_tv = (TextView) itemView.findViewById(R.id.tv_setfans);
        viewCounts_tv = (TextView) itemView.findViewById(R.id.tv_viewcount);
        name_tv = (TextView) itemView.findViewById(R.id.detail_name_tv);
        time_tv = (TextView) itemView.findViewById(R.id.detail_time_tv);
        intro_tv = (TextView) itemView.findViewById(R.id.tv_selfintro);
        lockReason_tv = (TextView) itemView.findViewById(R.id.locked_reason);
        lockUpdate_tv = (TextView) itemView.findViewById(R.id.update_btn);
        lockPost_tv = (TextView) itemView.findViewById(R.id.post_update_btn);
        viewCounts_ll = (LinearLayout) itemView.findViewById(R.id.viewcount);
        needFans_ll = (LinearLayout) itemView.findViewById(R.id.ll_needfans);
        lock_rl = (RelativeLayout) itemView.findViewById(R.id.ll_detail_locked);
        lockcontral_ll = (LinearLayout) itemView.findViewById(R.id.fix_container);
        lockCheck_tv = (TextView) itemView.findViewById(R.id.post_update_btn_lock);
        head_rl = (RelativeLayout) itemView.findViewById(R.id.rl_header_top);
        login_tv = (TextView) itemView.findViewById(R.id.tv_login);
        login_ll = (LinearLayout) itemView.findViewById(R.id.ll_needlogin);

        ivHeaderRightAction = (ImageView) itemView.findViewById(R.id.iv_header_right_action);
    }


    public void setData(Complex mItem, Context mContext) {

        this.mContext = mContext;
        this.complex = mItem;

        int maxNameWidth = CommonUtils.getWidthPixels((Activity) mContext) - UIUtils.dip2px(208, mContext);
        name_tv.setMaxWidth(maxNameWidth);

        if ((mItem.getStatus() == 1 || mItem.getStatus() == MyConstants.NEED_FANS) && mItem.getLock() == null) {
            if (mItem.getStatus() == 1) {
                if (mItem.getUid().equals(UserDataHelper.getInstance(mContext).getUid())) {
                    viewCounts_ll.setVisibility(View.VISIBLE);
                    focus_tv.setVisibility(View.INVISIBLE);
                    viewCounts_tv.setText(mItem.getView_count());
                } else {
                    if (mItem.getProfile().getFollowstate().equals("unfollow")) {
                        focus_tv.setVisibility(View.VISIBLE);
                    } else {
                        focus_tv.setVisibility(View.GONE);
                    }
                }
            }
            if (mItem.getStatus() == MyConstants.NEED_FANS) {
                needFans_ll.setVisibility(View.VISIBLE);
                focus_tv.setVisibility(View.GONE);
                ivHeaderRightAction.setVisibility(View.GONE);
            } else {
                ivHeaderRightAction.setVisibility(View.VISIBLE);
                processRightAction();
            }
            ImageLoader.getInstance().displayImage(mItem.getProfile().getAvatar(), circle_iv, ImageOptions.optionHead);
            name_tv.setText(mItem.getProfile().getUname());
            time_tv.setText(StringUtil.getOppositeTime(mItem.getCtime()));
            if (mItem.getProfile().isValue_user()) {
                vip_iv.setVisibility(View.VISIBLE);
            } else {
                vip_iv.setVisibility(View.GONE);
            }
            if (TextUtils.isEmpty(mItem.getProfile().getSelf_intro())) {
                intro_tv.setVisibility(View.GONE);
            } else {
                intro_tv.setVisibility(View.VISIBLE);
                intro_tv.setText(Html.fromHtml(mItem.getProfile().getSelf_intro()));
            }
            if (mItem.getTimelineType() == TimelineFactory.TIMELINE_TYPE_WRITER) {
                if (!TextUtils.isEmpty(mItem.getCover())) {
                    ImageLoader.getInstance().displayImage(mItem.getCover(), bg_iv, ImageOptions.options_none);
                }
            } else {
                if (!TextUtils.isEmpty(mItem.getBack_img())) {
                    new setBgTask(mItem.getBack_img()) {
                    }.execute();
                }
            }

        } else if (mItem.getStatus() == MyConstants.NEED_LOGIN) {
            login_ll.setVisibility(View.VISIBLE);
            login_tv.setVisibility(View.VISIBLE);
            head_rl.setVisibility(View.GONE);
        } else if (mItem.getStatus() == MyConstants.WORK_LOKED) {
            lock_rl.setVisibility(View.VISIBLE);
            head_rl.setVisibility(View.GONE);
            lockcontral_ll.setVisibility(View.GONE);
            setLock();
        } else if (mItem.getLock() != null) {
            head_rl.setVisibility(View.GONE);
            BaseObserver.getInstance().notifyWatchers(BaseObserver.DELETE);
            if (!TextUtils.isEmpty(mItem.getLock().getStatus()) && !mItem.getLock().getStatus().equals("locked")) {
                lockPost_tv.setVisibility(View.GONE);
                lockUpdate_tv.setVisibility(View.VISIBLE);
                lockCheck_tv.setVisibility(View.VISIBLE);
            } else {
                lockPost_tv.setVisibility(View.VISIBLE);
                lockUpdate_tv.setVisibility(View.VISIBLE);
                lockCheck_tv.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(mItem.getLock().getReason())) {
                lockReason_tv.setText(Html.fromHtml(mItem.getLock().getReason()));
            } else {
                setLock();
            }
            lock_rl.setVisibility(View.VISIBLE);
        }
        back_iv.setOnClickListener(this);
        name_tv.setOnClickListener(this);
        circle_iv.setOnClickListener(this);
        time_tv.setOnClickListener(this);
        intro_tv.setOnClickListener(this);
        login_tv.setOnClickListener(this);
        focus_tv.setOnClickListener(this);
        setFans_tv.setOnClickListener(this);
        lockUpdate_tv.setOnClickListener(this);
        lockPost_tv.setOnClickListener(this);

    }

    private void processRightAction() {
        Profile profile = complex.getProfile();
        if (null != profile) {
            ivHeaderRightAction.setVisibility(View.VISIBLE);
            if (StringUtil.notNullEqual(profile.getUid(), UserDataHelper.getInstance(mContext).getUid())) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ivHeaderRightAction.setImageDrawable(mContext.getResources().getDrawable(R.drawable.detail_more, mContext.getTheme()));
                } else {
                    ivHeaderRightAction.setImageDrawable(mContext.getResources().getDrawable(R.drawable.detail_more));
                }
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ivHeaderRightAction.setImageDrawable(mContext.getResources().getDrawable(R.drawable.share_actionbar, mContext.getTheme()));
                } else {
                    ivHeaderRightAction.setImageDrawable(mContext.getResources().getDrawable(R.drawable.share_actionbar));
                }
            }
            ivHeaderRightAction.setOnClickListener(this);
        } else {
            ivHeaderRightAction.setVisibility(View.GONE);
        }
    }

    private void setLock() {
        switch (complex.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                lockReason_tv.setText(mContext.getString(R.string.cos_locked_one));
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                lockReason_tv.setText(mContext.getString(R.string.draw_locked_one));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                lockReason_tv.setText(mContext.getString(R.string.write_locked_one));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                lockReason_tv.setText(mContext.getString(R.string.daily_locked_one));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_top:
                BaseObserver.getInstance().notifyWatchers(BaseObserver.FINISH_EVENT);
                break;
            case R.id.detail_head_img:
            case R.id.detail_name_tv:
            case R.id.tv_selfintro:
            case R.id.detail_time_tv:
                BaseObserver.getInstance().notifyWatchers(BaseObserver.GO_PERSON);
                break;
            case R.id.tv_focuse:
                TimelineLikeHelper.doFollow(mContext, "dofollow", complex.getProfile().getUid(), new TimelineLikeHelper.FollowSuccess() {
                    @Override
                    public void onFollowSuccess(String response) {
                        if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                            MyToast.show(mContext, mContext.getString(R.string.focus_succ));
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.FOLLOW_EVENT);
                        }
                    }
                });
                break;
            case R.id.tv_setfans:
                TimelineLikeHelper.doFollow(mContext, "dofollow", complex.getProfile().getUid(), new TimelineLikeHelper.FollowSuccess() {
                    @Override
                    public void onFollowSuccess(String response) {
                        if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                            MyToast.show(mContext, mContext.getString(R.string.focus_succ));
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.FOLLOW_EVENT_REFREASH);
                        }
                    }
                });
                break;
            case R.id.update_btn:
                goEdit();
                break;
            case R.id.post_update_btn:
                postUpdate();
                break;
            case R.id.iv_header_right_action:
                BaseObserver.getInstance().notifyWatchers(BaseObserver.SHARE_EVENT);
                break;
            case R.id.tv_login:
                gotoUtil.gotoAct(mContext, LoginActivity.class);
                break;
        }
    }

    private void postUpdate() {
        IlockedInter ilockedInter = new IlockedInter() {
            @Override
            public void succ(String s) {
                lockPost_tv.setVisibility(View.GONE);
                lockCheck_tv.setVisibility(View.VISIBLE);
            }

            @Override
            public void fail() {
                MyToast.show(mContext, mContext.getString(R.string.operation_fail));
            }
        };
        LockedHelper lockedHelper = new LockedHelper(mContext, ilockedInter);
        lockedHelper.postUpdate(complex);
    }

    private void goEdit() {
        Intent intent = new Intent();
        DetailType detailType = new DetailType();
        switch (complex.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_COSER);
                detailType.setCp_id(complex.getCp_id());
                detailType.setRp_id(complex.getRp_id());
                intent.putExtra("edit_data", detailType);
                intent.setClass(mContext, CosEditActivity.class);
                mContext.startActivity(intent);
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_ILLUST);
                detailType.setDp_id(complex.getDp_id());
                detailType.setRp_id(complex.getRp_id());
                intent.putExtra("edit_data", detailType);
                intent.setClass(mContext, illustEditActivity.class);
                mContext.startActivity(intent);
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_DAILY);
                detailType.setUd_id(complex.getUd_id());
                intent.putExtra("edit_data", detailType);
                intent.setClass(mContext, DailyEditActivity.class);
                mContext.startActivity(intent);
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_WRITER);
                detailType.setRp_id(complex.getRp_id());
                detailType.setWp_id(complex.getWp_id());
                intent.putExtra("edit_data", detailType);
                intent.setClass(mContext, EditArticleActivity.class);
                mContext.startActivity(intent);
                break;
        }
    }


    private class setBgTask extends AsyncTask<Void, Void, Bitmap> {

        protected String mfile;

        setBgTask(String mfile) {
            this.mfile = mfile;
        }

        @Override
        protected Bitmap doInBackground(Void... p) {
            try {
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inSampleSize = 4;
                File file = new File(mfile);
                byte[] result = ByteUtils.parseImageToByte(file);
                Bitmap bm = BitmapFactory.decodeByteArray(result, 0, result.length, opts);
                Bitmap overlay = ImageManager.fastblur(ThumbnailUtils.extractThumbnail(bm, 200, 200), 20);
                bm = null;
                return overlay;
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bm) {
            if (bm != null) bg_iv.setImageBitmap(bm);
        }
    }

}
